import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../utils/themes/app_theme.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../services/theme_service.dart';
import '../../../routes/app_routes.dart';
import '../controllers/thing_model_editor_controller.dart';

class ThingModelEditorView extends GetView<ThingModelEditorController> {
  const ThingModelEditorView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final extension = AppTheme.extensionOf(context);
    final themeService = Get.find<ThemeService>();

    return Scaffold(
      appBar: AppBar(
        title: const Text('物模型编辑'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.file_upload),
            tooltip: '导入JSON',
            onPressed: _importFromJson,
          ),
          IconButton(
            icon: const Icon(Icons.file_download),
            tooltip: '导出JSON',
            onPressed: _exportToJson,
          ),
          Obx(() => controller.isSaving.value
            ? Container(
                padding: const EdgeInsets.all(12),
                child: const CircularProgressIndicator(strokeWidth: 2)
              )
            : IconButton(
                icon: const Icon(Icons.save),
                onPressed: _saveModel,
              )
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.hasError.value) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, size: 48, color: extension.errorText),
                const SizedBox(height: 16),
                Text(
                  controller.errorMessage.value,
                  style: theme.textTheme.bodyLarge?.copyWith(color: extension.errorText),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: controller.loadThingModel,
                  child: const Text('重试'),
                ),
              ],
            ),
          );
        }

        return Column(
          children: [
            // 选项卡
            TabBar(
              controller: controller.tabController,
              labelColor: themeService.getThemedColor(
                lightColor: theme.primaryColor,
                darkColor: Colors.white,
              ),
              indicatorColor: theme.primaryColor,
              tabs: const [
                Tab(text: '属性'),
                Tab(text: '服务'),
                Tab(text: '事件'),
              ],
            ),
            
            // 内容区域
            Expanded(
              child: TabBarView(
                controller: controller.tabController,
                children: [
                  _buildPropertiesView(theme, extension),
                  _buildServicesView(theme, extension),
                  _buildEventsView(theme, extension),
                ],
              ),
            ),
          ],
        );
      }),
      floatingActionButton: Obx(() {
        // 根据当前选项卡显示不同的添加按钮
        Widget fab;
        switch (controller.currentTabIndex.value) {
          case 0:
            fab = FloatingActionButton(
              onPressed: controller.addProperty,
              tooltip: '添加属性',
              child: const Icon(Icons.add),
            );
            break;
          case 1:
            fab = FloatingActionButton(
              onPressed: controller.addService,
              tooltip: '添加服务',
              child: const Icon(Icons.add),
            );
            break;
          case 2:
            fab = FloatingActionButton(
              onPressed: controller.addEvent,
              tooltip: '添加事件',
              child: const Icon(Icons.add),
            );
            break;
          default:
            fab = const SizedBox.shrink();
        }
        return fab;
      }),
    );
  }

  // 保存模型
  Future<void> _saveModel() async {
    await controller.saveThingModel();
  }
  
  // 导入JSON
  void _importFromJson() {
    final TextEditingController jsonController = TextEditingController();
    
    Get.dialog(
      AlertDialog(
        title: const Text('导入物模型JSON'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('请粘贴物模型JSON数据'),
            const SizedBox(height: 12),
            Container(
              height: 300, 
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(4)
              ),
              child: TextField(
                controller: jsonController,
                maxLines: null,
                expands: true,
                decoration: const InputDecoration(
                  contentPadding: EdgeInsets.all(8),
                  border: InputBorder.none,
                  hintText: '在此粘贴JSON数据...'
                ),
              ),
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: () => Get.toNamed(Routes.JSON_TEST),
                  child: const Text('测试解析'),
                ),
                Text('支持带转义字符的JSON', style: TextStyle(fontSize: 12, color: Colors.grey[600])),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final jsonString = jsonController.text.trim();
              if (jsonString.isEmpty) {
                Get.snackbar(
                  '错误', 
                  'JSON数据不能为空',
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: Colors.red.shade100,
                  colorText: Colors.red.shade900
                );
                return;
              }
              
              // 调用控制器方法导入JSON
              controller.importFromJson(jsonString);
              Get.back();
            },
            child: const Text('导入'),
          ),
        ],
      ),
    );
  }
  
  // 导出JSON
  void _exportToJson() {
    final modelJson = controller.getModelJson();
    final jsonString = controller.formatJsonString(modelJson);
    
    Get.dialog(
      AlertDialog(
        title: const Text('物模型JSON数据'),
        content: Container(
          height: 300,
          width: 500,
          decoration: BoxDecoration(
            color: Colors.grey.shade100,
            borderRadius: BorderRadius.circular(8),
          ),
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: SelectableText(
              jsonString,
              style: const TextStyle(fontFamily: 'monospace'),
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  // 构建属性列表视图
  Widget _buildPropertiesView(ThemeData theme, AppThemeExtension extension) {
    return Obx(() {
      if (controller.thingModel.value == null || controller.properties.isEmpty) {
        return _buildEmptyView('暂无属性', '点击 + 按钮添加属性');
      }
      
      return ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: controller.properties.length,
        itemBuilder: (context, index) {
          final property = controller.properties[index];
          return _buildPropertyCard(property, index, theme, extension);
        },
      );
    });
  }

  // 构建单个属性卡片
  Widget _buildPropertyCard(
    Map<String, dynamic> property, 
    int index, 
    ThemeData theme, 
    AppThemeExtension extension
  ) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '属性: ${property['name'] ?? "新属性"}',
                  style: theme.textTheme.titleMedium,
                ),
                IconButton(
                  icon: Icon(Icons.delete, color: extension.errorText),
                  onPressed: () => controller.deleteProperty(property['id']),
                ),
              ],
            ),
            const Divider(),
            _buildTextField(
              '标识符',
              property['identifier'] ?? '',
              (value) {
                property['identifier'] = value;
                controller.updateProperty(index, property);
              },
              theme,
            ),
            _buildTextField(
              '名称',
              property['name'] ?? '',
              (value) {
                property['name'] = value;
                controller.updateProperty(index, property);
              },
              theme,
            ),
            _buildDropdownField(
              '数据类型',
              property['dataType'] ?? 'string',
              controller.getDataTypeOptions(),
              (value) {
                property['dataType'] = value;
                controller.updateProperty(index, property);
              },
              theme,
            ),
            _buildDropdownField(
              '读写类型',
              property['accessMode'] ?? 'rw',
              const ['r', 'rw'],
              (value) {
                property['accessMode'] = value;
                controller.updateProperty(index, property);
              },
              theme,
              itemBuilder: (value) => value == 'r' ? '只读' : '读写',
            ),
            _buildTextField(
              '描述',
              property['description'] ?? '',
              (value) {
                property['description'] = value;
                controller.updateProperty(index, property);
              },
              theme,
              maxLines: 3,
            ),
          ],
        ),
      ),
    );
  }

  // 构建服务列表视图
  Widget _buildServicesView(ThemeData theme, AppThemeExtension extension) {
    return Obx(() {
      if (controller.thingModel.value == null || controller.services.isEmpty) {
        return _buildEmptyView('暂无服务', '点击 + 按钮添加服务');
      }
      
      return ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: controller.services.length,
        itemBuilder: (context, index) {
          final service = controller.services[index];
          return _buildServiceCard(service, index, theme, extension);
        },
      );
    });
  }

  // 构建单个服务卡片
  Widget _buildServiceCard(
    Map<String, dynamic> service, 
    int index, 
    ThemeData theme, 
    AppThemeExtension extension
  ) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '服务: ${service['name'] ?? "新服务"}',
                  style: theme.textTheme.titleMedium,
                ),
                IconButton(
                  icon: Icon(Icons.delete, color: extension.errorText),
                  onPressed: () => controller.deleteService(service['id']),
                ),
              ],
            ),
            const Divider(),
            _buildTextField(
              '标识符',
              service['identifier'] ?? '',
              (value) {
                service['identifier'] = value;
                controller.updateService(index, service);
              },
              theme,
            ),
            _buildTextField(
              '名称',
              service['name'] ?? '',
              (value) {
                service['name'] = value;
                controller.updateService(index, service);
              },
              theme,
            ),
            _buildTextField(
              '描述',
              service['description'] ?? '',
              (value) {
                service['description'] = value;
                controller.updateService(index, service);
              },
              theme,
              maxLines: 3,
            ),
            
            // 输入参数
            const SizedBox(height: 16),
            Text('输入参数', style: theme.textTheme.titleSmall),
            const SizedBox(height: 8),
            _buildParameterSection(
              theme, 
              extension, 
              service['input'] ?? [], 
              (params) {
                service['input'] = params;
                controller.updateService(index, service);
              }
            ),
            
            // 输出参数
            const SizedBox(height: 16),
            Text('输出参数', style: theme.textTheme.titleSmall),
            const SizedBox(height: 8),
            _buildParameterSection(
              theme, 
              extension, 
              service['output'] ?? [], 
              (params) {
                service['output'] = params;
                controller.updateService(index, service);
              }
            ),
          ],
        ),
      ),
    );
  }

  // 构建事件列表视图
  Widget _buildEventsView(ThemeData theme, AppThemeExtension extension) {
    return Obx(() {
      if (controller.thingModel.value == null || controller.events.isEmpty) {
        return _buildEmptyView('暂无事件', '点击 + 按钮添加事件');
      }
      
      return ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: controller.events.length,
        itemBuilder: (context, index) {
          final event = controller.events[index];
          return _buildEventCard(event, index, theme, extension);
        },
      );
    });
  }

  // 构建单个事件卡片
  Widget _buildEventCard(
    Map<String, dynamic> event, 
    int index, 
    ThemeData theme, 
    AppThemeExtension extension
  ) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '事件: ${event['name'] ?? "新事件"}',
                  style: theme.textTheme.titleMedium,
                ),
                IconButton(
                  icon: Icon(Icons.delete, color: extension.errorText),
                  onPressed: () => controller.deleteEvent(event['id']),
                ),
              ],
            ),
            const Divider(),
            _buildTextField(
              '标识符',
              event['identifier'] ?? '',
              (value) {
                event['identifier'] = value;
                controller.updateEvent(index, event);
              },
              theme,
            ),
            _buildTextField(
              '名称',
              event['name'] ?? '',
              (value) {
                event['name'] = value;
                controller.updateEvent(index, event);
              },
              theme,
            ),
            _buildDropdownField(
              '事件类型',
              event['type'] ?? 'info',
              const ['info', 'alert', 'error'],
              (value) {
                event['type'] = value;
                controller.updateEvent(index, event);
              },
              theme,
              itemBuilder: (value) {
                switch (value) {
                  case 'info': return '信息';
                  case 'alert': return '告警';
                  case 'error': return '故障';
                  default: return value;
                }
              },
            ),
            _buildTextField(
              '描述',
              event['description'] ?? '',
              (value) {
                event['description'] = value;
                controller.updateEvent(index, event);
              },
              theme,
              maxLines: 3,
            ),
            
            // 事件参数
            const SizedBox(height: 16),
            Text('事件参数', style: theme.textTheme.titleSmall),
            const SizedBox(height: 8),
            _buildParameterSection(
              theme, 
              extension, 
              event['params'] ?? [], 
              (params) {
                event['params'] = params;
                controller.updateEvent(index, event);
              }
            ),
          ],
        ),
      ),
    );
  }
  
  // 构建参数编辑部分
  Widget _buildParameterSection(
    ThemeData theme,
    AppThemeExtension extension,
    List<dynamic> params,
    Function(List<dynamic>) onParamsChanged,
  ) {
    // 转换为正确类型
    List<Map<String, dynamic>> paramList = [];
    for (var param in params) {
      if (param is Map<String, dynamic>) {
        paramList.add(param);
      } else if (param is Map) {
        paramList.add(Map<String, dynamic>.from(param));
      }
    }
    
    return Column(
      children: [
        ...paramList.asMap().entries.map((entry) {
          int idx = entry.key;
          Map<String, dynamic> param = entry.value;
          
          return Card(
            margin: const EdgeInsets.only(bottom: 8),
            color: extension.cardBackground,
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('参数 #${idx + 1}', style: theme.textTheme.bodyMedium),
                      IconButton(
                        icon: Icon(Icons.delete, color: extension.errorText, size: 20),
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(),
                        onPressed: () {
                          paramList.removeAt(idx);
                          onParamsChanged(paramList);
                        },
                      ),
                    ],
                  ),
                  _buildTextField(
                    '标识符',
                    param['identifier'] ?? '',
                    (value) {
                      param['identifier'] = value;
                      onParamsChanged(paramList);
                    },
                    theme,
                    dense: true,
                  ),
                  _buildTextField(
                    '名称',
                    param['name'] ?? '',
                    (value) {
                      param['name'] = value;
                      onParamsChanged(paramList);
                    },
                    theme,
                    dense: true,
                  ),
                  _buildDropdownField(
                    '数据类型',
                    param['dataType'] ?? 'string',
                    controller.getDataTypeOptions(),
                    (value) {
                      param['dataType'] = value;
                      onParamsChanged(paramList);
                    },
                    theme,
                    dense: true,
                  ),
                ],
              ),
            ),
          );
        }).toList(),
        
        // 添加参数按钮
        TextButton.icon(
          icon: const Icon(Icons.add, size: 18),
          label: const Text('添加参数'),
          onPressed: () {
            paramList.add({
              'identifier': 'param_${paramList.length + 1}',
              'name': '参数${paramList.length + 1}',
              'dataType': 'string'
            });
            onParamsChanged(paramList);
          },
        ),
      ],
    );
  }

  // 构建空视图
  Widget _buildEmptyView(String title, String subtitle) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.info_outline, size: 48, color: Colors.grey.withOpacity(0.5)),
          const SizedBox(height: 16),
          Text(
            title,
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Text(
            subtitle,
            style: TextStyle(color: Colors.grey.shade600),
          ),
        ],
      ),
    );
  }

  // 构建文本输入字段
  Widget _buildTextField(
    String label,
    String value,
    Function(String) onChanged,
    ThemeData theme, {
    int maxLines = 1,
    bool dense = false,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: dense ? 4 : 8),
      child: TextField(
        controller: TextEditingController(text: value),
        decoration: InputDecoration(
          labelText: label,
          border: const OutlineInputBorder(),
          contentPadding: dense 
            ? const EdgeInsets.symmetric(horizontal: 12, vertical: 8)
            : null,
        ),
        style: dense ? theme.textTheme.bodySmall : null,
        maxLines: maxLines,
        onChanged: onChanged,
      ),
    );
  }

  // 构建下拉选择字段
  Widget _buildDropdownField(
    String label,
    String value,
    List<String> options,
    Function(String) onChanged,
    ThemeData theme, {
    Function(String)? itemBuilder,
    bool dense = false,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: dense ? 4 : 8),
      child: DropdownButtonFormField<String>(
        value: value,
        decoration: InputDecoration(
          labelText: label,
          border: const OutlineInputBorder(),
          contentPadding: dense 
            ? const EdgeInsets.symmetric(horizontal: 12, vertical: 8)
            : null,
        ),
        style: dense ? theme.textTheme.bodySmall : null,
        items: options.map((String option) {
          return DropdownMenuItem<String>(
            value: option,
            child: Text(itemBuilder != null ? itemBuilder(option) : option),
          );
        }).toList(),
        onChanged: (String? newValue) {
          if (newValue != null) {
            onChanged(newValue);
          }
        },
      ),
    );
  }
} 